package com.benjaminwan.read.free.ui.operation

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.airbnb.mvrx.activityViewModel
import com.airbnb.mvrx.withState
import com.benjaminwan.read.free.R
import com.benjaminwan.read.free.base.adapter.simpleController
import com.benjaminwan.read.free.base.fragment.BaseFragment
import com.benjaminwan.read.free.databinding.FragmentOperationBinding
import com.benjaminwan.read.free.model.action.Position
import com.benjaminwan.read.free.ui.main.MainState
import com.benjaminwan.read.free.ui.main.MainViewModel
import com.benjaminwan.read.free.utils.setMarginItemDecoration
import com.benjaminwan.read.free.views.actionItemView
import com.orhanobut.logger.Logger

class OperationFragment : BaseFragment(), View.OnClickListener {

    private val mainVM by activityViewModel(MainViewModel::class)
    private val epoxyController by lazy { epoxyController() }

    private lateinit var binding: FragmentOperationBinding

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentOperationBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        epoxyController.onRestoreInstanceState(savedInstanceState)
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        epoxyController.onSaveInstanceState(outState)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViews()
    }

    private fun initViews() {
        binding.actionListRv.setHasFixedSize(true)
        binding.actionListRv.setMarginItemDecoration(2, 1, 2, 1)
        binding.actionListRv.setController(epoxyController)
        binding.startBtn.setOnClickListener(this)
        binding.stopBtn.setOnClickListener(this)
    }

    override fun onClick(view: View?) {
        view ?: return
        when (view.id) {
            R.id.startBtn -> {
                mainVM.startScript()
            }

            R.id.stopBtn -> {
                mainVM.stopScript()
                binding.stopBtn.text = "停止中..."
            }

            else -> {
            }
        }
    }

    private fun calcItemCount(pos: Position, main: MainState): Int {
        var count = 0
        main.script.groups.forEachIndexed { index, group ->
            if (index < pos.idGroup) {
                count += group.actions.size
            }
        }
        return count + pos.idGroup + pos.idAction + 3
    }

    override fun invalidate() = withState(mainVM) { main ->
        requireActivity().invalidateOptionsMenu()
        binding.actionListRv.requestModelBuild()
        val pos = calcItemCount(main.currentPos, main)
        Logger.i("pos=$pos")
        if (pos < epoxyController.adapter.itemCount) {
            binding.actionListRv.scrollToPosition(pos)
        }
        binding.startBtn.isEnabled = !main.isScriptRunning
        binding.stopBtn.isEnabled = main.isScriptRunning
        if (!main.isScriptRunning) {
            binding.stopBtn.text = "停止"
        }
    }

    private fun epoxyController() = simpleController(mainVM) { main ->
        val script = main.script
        val scriptProgress = if (main.scriptProgress.progress > 0 && main.scriptProgress.max >= 0)
            "进度:${main.scriptProgress.progress}/${main.scriptProgress.max}" else ""
        Logger.i(scriptProgress)
        actionItemView {
            id("ScriptRunGlobal:${script.hashCode()}")
            actionIndex("Global")
            actionType("Config(${main.script.memo})")
            actionProgress(scriptProgress)
            actionParam(script.toString())
            backgroundRes(R.drawable.bg_red5_to_red7)
        }
        script.groups.forEachIndexed { idGroup, group ->
            val groupProgress =
                if (main.groupProgress.idGroup == idGroup && main.groupProgress.progress > 0 && main.groupProgress.max > 0)
                    "进度:${main.groupProgress.progress}/${main.groupProgress.max}" else ""
            Logger.i(groupProgress)
            actionItemView {
                id("ScriptRunGroup:${idGroup}${script.hashCode()}${group.hashCode()}")
                actionIndex("G${idGroup + 1}")
                actionType("Group${idGroup + 1}(${group.memo})")
                actionProgress(groupProgress)
                actionParam(group.toString())
                if (main.currentPos.idGroup == idGroup) {
                    backgroundRes(R.drawable.bg_orange5_to_orange7)
                } else {
                    backgroundRes(R.drawable.bg_grey5_to_grey7)
                }
                marginLeft(0)
            }
            group.actions.forEachIndexed { idAction, action ->
                actionItemView {
                    id("ScriptRunAction:${idGroup}:${idAction}${script.hashCode()}${group.hashCode()}${action.hashCode()}")
                    actionIndex("A${idAction + 1}")
                    actionType(action.actionType.name)
                    actionParam(action.toString())
                    if (main.currentPos.idGroup == idGroup && main.currentPos.idAction == idAction) {
                        backgroundRes(R.drawable.bg_blue5_to_blue7)
                    } else {
                        backgroundRes(R.drawable.bg_grey5_to_grey7)
                    }
                    marginLeft(1)
                }
            }
        }
    }

}